<template>
  <div>
    <ElementDialog :title="title" :visible.sync="upload.open" width="400px" append-to-body>
      <ElUpload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="headers"
        :action="url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <ElLink
              v-if="tempUrl"
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="downExcelTemp">
              下载模板
            </ElLink>
          </div>
        </template>
      </ElUpload>
      <template #footer>
        <div class="dialog-footer">
          <ElButton size="small" type="primary" @click="submitFileForm">确 定</ElButton>
          <ElButton size="small" @click="upload.open = false">取 消</ElButton>
        </div>
      </template>
    </ElementDialog>

    <!--校验失败错误数据-->
    <ElementDialog title="校验失败数据" :visible.sync="errorVisible">
      <ElTable :data="errorData">
        <ElTableColumn property="lineNum" label="行号" width="50" />
        <ElTableColumn property="errors" label="错误描述" show-overflow-tooltip>
          <template #default="scope">
            <ElTag v-for="error in scope.row.errors" :key="error" type="danger">
              {{ error }}
            </ElTag>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElementDialog>
  </div>
</template>

<script>
  import { getToken } from '@/util/auth'
  import { mapState } from 'vuex'

  export default {
    name: 'Excel',
    components: {},
    props: {
      url: {
        type: String
      },
      title: {
        type: String
      },
      tempUrl: {
        type: String
      },
      tempName: {
        type: String,
        default: 'temp.xlsx'
      }
    },
    data() {
      return {
        upload: {
          open: false,
          isUploading: false
        },
        errorVisible: false,
        errorData: []
      }
    },
    computed: {
      ...mapState('user', ['sysUser']),
      headers() {
        const tenantId = this.sysUser.tenantId
        return {
          Authorization: `Bearer ${getToken()}`,
          'TENANT-ID': tenantId || '1'
        }
      }
    },
    methods: {
      downExcelTemp() {
        this.$downBlobFile(this.tempUrl, {}, this.tempName)
      },
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      handleFileError() {
        this.$message.error('上传失败,数据格式不合法!')
        this.upload.open = false
      },
      handleFileSuccess(response) {
        this.upload.isUploading = false
        this.upload.open = false
        this.$refs.upload.clearFiles()

        // 校验失败
        if (response.code === 1) {
          this.$refs.upload.clearFiles()
          let errorMsg = ''
          if (this.$isBlank(response.data)) {
            errorMsg = response.msg
          }
          for (const dataKey in response.data) {
            const data = response.data[dataKey]
            errorMsg += `<p>第${data.lineNum}行：${data.errors} </p>`
          }
          // this.$message.error(`导入失败，以下数据不合法:${errorMsg}`)
          this.$message({
            type: 'error',
            dangerouslyUseHTMLString: true,
            message: errorMsg
          })
        } else {
          this.$message.success('导入成功')
          // 刷新表格
          this.$emit('refreshDataList')
        }
      },
      submitFileForm() {
        this.$refs.upload.submit()
      },
      show() {
        this.upload.isUploading = false
        this.upload.open = true
      }
    }
  }
</script>
